<?php

/*
 * 
 * 这个页面专门用来针对 投票活动
 * 现阶段是年货
 * 
 * 1. 年货首页
 * 2. 年货活动发起
 * 3. 年货活动投票页面
 * 4. 排行榜
 * 5. 年货首页（按人气排行）
 * 
 * 
 */
namespace M\Controller;
use Think\Controller;
class VoteController extends CommonController{
    

    
    public function index() {
        /*
         * 增加页面访问量
         */
        $this->add_pv();
        
        
        /*
         * 判断是什么样的排序类型
         * 1. 按照时间
         * 3. 按照人气
         * 
         */
//        
        $type = I("get.type");
        $vsid = I("get.vsid"); //默认是年货活动
        
        $idnum = I("get.idnum");
        if(!empty($idnum))
        {
            $map['id']=$idnum;
            
        }
        
        if($type==1)
        {
            //按照人气排行
            $DB = M("vote_options");
            if(empty($vsid))
            {
                $vsid=1;
            }
            
            $map['vsid']=$vsid;
            $map['ishidden']=0;
            
//            $res = $DB->where($map)->select();
            
            $count      = $DB->where($map)->count();// 查询满足要求的总记录数
            $Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
            $show       = $Page->show();// 分页显示输出
            //
            $res = $DB->where($map)->order('rank,vote_count DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
                    //
            //找出封面图片
            foreach ($res as $key => $value) {
                $res[$key]['thumb_list']=  $this->get_one_thumb_list($value['img_ids']);
            }
            
            $this->assign('page',$show);// 赋值分页输出
            $this->assign("result", $res);
        }
        else
        {
            /*
         * 更新排名
         */
        $this->refresh_rank();
        
//            默认按照时间排序
            $DB = M("vote_options");
            if(empty($vsid))
            {
                $vsid=1;
            }
            
            $map['vsid']=$vsid;
            $map['ishidden']=0;
            
//            $res = $DB->where($map)->select();
            
            $count      = $DB->where($map)->count();// 查询满足要求的总记录数
            $Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
            $show       = $Page->show();// 分页显示输出
            //
            $res = $DB->where($map)->order('ctime DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
                    //
            //找出封面图片
            foreach ($res as $key => $value) {
                $res[$key]['thumb_list']=  $this->get_one_thumb_list($value['img_ids']);
            }
            
            $this->assign('page',$show);// 赋值分页输出
            $this->assign("result", $res);
//            print_r($res);
            
//            print_r($DB->getLastSql());
        }
        
        $initial_info = $this->_initial_info();
        $this->assign("initial_info", $initial_info);
        $this->assign('type', $type);
        
        $this->display();
    }
    
    /*
     * 年货发起
     */
    public function create() {
        /*
         * 增加页面访问量
         */
        $this->add_pv();
        
        if(IS_POST)
        {
            //根据提交的内容创建投票选项
            $vsid = I("post.vsid");
            
            if(empty($vsid))
            {
                $vsid=1;
            }
            $mid = $this->memberinfo['id'];
            $map['mid']=$mid;
            $map['vsid']=$vsid;

            $ressss = M("vote_options")->where($map)->find();
            /*
            * 判断用户是否已经发起过了活动
            * 是的话，则跳进对应的投票详情页面
            * 
            */
            if(!empty($ressss))
            {
                //跳转到详情页面去
                $result['id']=0; 
                echo json_encode($result);
                exit();
            }
            
            
            $content = trim(I("post.content"));
            $data['vsid']=$vsid;
            $data['mid']=  $this->memberinfo['id'];
            $data['openid']=  session("openid");
            $data['ctime']=I("server.REQUEST_TIME");
            $wx_media_ids = trim(I("post.wx_media_ids"));
//            $data['wx_media_ids']=$wx_media_ids;
            
            /*
             * 根据media id 来下载图片到本地数据库
             */
            if(!empty($wx_media_ids))
            {
                $accessToken = $this->accessToken;
                    
                $wx_media_arr = json_decode(htmlspecialchars_decode($wx_media_ids),true);
                $sampleids = "";
                $targetName_arr = array();
                foreach ($wx_media_arr as $key => $value) {
                    $filename = date('YmdHis').$this->random_code().'.jpg';
                    $targetName = "./Uploads/fundings/wx_media/".$filename;
                    
                    array_push($targetName_arr, $targetName);
                    
                    $ch = curl_init("http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=$accessToken&media_id=$value");
                    $fp = fopen($targetName, 'wb');
                    curl_setopt($ch, CURLOPT_FILE, $fp);
                    curl_setopt($ch, CURLOPT_HEADER, 0);
                    curl_exec($ch);
                    curl_close($ch);
                    fclose($fp);
                    
                    /*
                     * 插入记录
                     * 1. 插入到 image 表 并得到返回的id写入 sampleid
                     */
                   $id[$key] = $this->insert_image(substr($targetName, 1));
                   $sampleids .=$id[$key].",";
                    
                    
                }
            
                //用户前端上传的图片保存位置
                $data['img_ids'] = substr($sampleids, 0,-1);
                
                $data['wx_media_ids']=serialize($wx_media_ids);
                
                /*
                * 处理第一张图片就是默认的图片
                */
//               print_r($targetName_arr);
//               exit();
               if(!empty($targetName_arr))
               {
                   $data['thumb']=$targetName_arr[0];
               }
            }
            
            
            $data['content']= $content;
            $now_count = M("vote_options")->count();
            if($now_count>0)
            {
                $data['rank']  =M("vote_options")->count();
            }
            else
            {
                $data['rank']=1;
            }
            
            $cash_code = $this->create_ramdon_code();
            
            $DB = M("vote_options");
            
            $id = $DB->add($data);
            
            if($id)
            {
                
                
                //获取推广的关注二维码
                $qrcode_url = $this->create_qrcode($id);
                $DB->id = $id;
                $DB->qrcode_url = $qrcode_url;
                $DB->cash_code = $cash_code;
                $DB->save();
                $result['id']=$id; 
                echo json_encode($result);
            }
            else
            {
                echo 0;
            }
            
            

            
        }
        else
        {
            
            /*
             *  判断用户是否是关注的用户
             */
            $openid = $this->memberinfo['wxopenid'];
            
            $res_if_member = $this->chk_member_is_fan($openid);
            
            if(!$res_if_member)
            {
                redirect(U("M/Vote/index",array("vsid"=>1)));
                exit();
            }
            
            
            $vsid = I("get.vsid"); //默认是年货活动
            if(empty($vsid))
            {
                $vsid=1;
            }
            $mid = $this->memberinfo['id'];
            $map['mid']=$mid;
            $map['vsid']=$vsid;

            $res = M("vote_options")->where($map)->find();

            if(empty($res))
            {
//                echo "1";
                $DB_vote_specials = M("vote_specials");
                $vs_res = $DB_vote_specials->find($vsid);
//                print_r($vs_res);
                if($vs_res['etime']<I("server.REQUEST_TIME"))
                {
                    
                    $this->assign("if_activity_expired", 1);
                }
                else {
                    $this->assign("if_activity_expired", 0);
                }
        
                //发起活动
                $initial_info = $this->_initial_info();
                $this->assign("initial_info", $initial_info);
                $this->assign('vsid', $vsid);
                $this->display();


            }
            else
            {
                //跳转到详情页面去
                redirect(U('M/Vote/vote_detail',array('vid'=>$res['id'])));
            }
           
        }
        
        
        
        
        
        
    }
    
    /*
     * detail 跳转
     */
    public function detail() {
        $vid = I("get.vid");
        
        redirect(U("vote_deail",array("vid"=>$vid)));
    }
    
    /*
     * 年货投票详情
     */
    public function vote_detail() {
        
        /*
         * 增加页面访问量
         */
        $this->add_pv();
        
        $vid = I("get.vid");
        
        $promotion = I("get.promotion");
        if(empty($promotion))
        {
            $promotion=0;
        }
        
        $DB = M("vote_options");
        
        //获取投票项目的详情
        $res = $DB->find($vid);
        
        if(empty($res))
        {
            //没信息跳转到 首页去
            redirect(U('M/Vote/index'));
        }
        //获取发起人的信息
        $member = M("members")->find($res['mid']);
        
        $res['avatar'] = $member['avatar'];
        $res['username'] = $member['username'];
        
        $res['thumb_list']=  $this->get_one_thumb_list($res['img_ids']);
        
        $this->assign('result', $res);
        
//        print_r($res);
        $this->assign('promotion', $promotion);
        $this->assign("ip", get_client_ip());
        $this->display();
        
        
    }
    
    
    /*
     * 直接进入投票功能并弹出
     */
    public function vote_detail_from_wx() {
        //判断有没有投票过
        
        /*
         * 增加页面访问量
         */
        $this->add_pv();
        
        $vid = I("get.vid");
        $openid = $this->memberinfo['wxopenid'];
        $mid = $this->memberinfo['id'];
        $cdate = date("Ymd",I('server.REQUEST_TIME'));
        
        
        if($this->chk_member_is_fan($openid))
        {
            /*
             * 判断是否是自己给自己投票
             */
            $res_v_option = M("vote_options")->find($vid);
            
            if(!empty($res_v_option))
            {
                if($mid===$res_v_option['mid'])
                {
                    //自己的投票跳转到自己的页面去
                    redirect(U('M/Vote/vote_detail',array('vid'=>$vid,'promotion'=>1)));
                    
                }
            }
            
            if(!$this->chk_if_vote_repeat($openid, $cdate))
            {
                $DB = M("vote_records");

                $map['vid']=$vid;
                $map['mid']=$mid;
                $map['cdate']=date("Ymd",I('server.REQUEST_TIME'));
                $map['ctime']=I('server.REQUEST_TIME');
                $map['openid']=$openid;

                $id = $DB->add($map);
                
                /*
                 * 投票加1
                 * 
                 */
                $DB_options = M("vote_options");
                $DB_options->where("id=".$vid)->setInc("vote_count");
                
                $this->assign("show_img", "http://".I('server.HTTP_HOST')."/"."Public/template/default/img/vote/share_bg_01.png");
                $this->assign('show_type', 1);
                

                
                
            }
            else 
            {
                //投票失败，不能重复投票
                $this->assign("show_img", "http://".I('server.HTTP_HOST')."/"."Public/template/default/img/vote/share_bg_02.png");
                $this->assign('show_type', 2);
            }
            
            

        }
        else
        {
//            还不是关注用户，不能参与投票，返回关注的二维码链接
//            $this->assign("show_img", "http://".I('server.HTTP_HOST')."/"."Public/template/default/img/vote/share_bg_01.png");
            $this->assign("show_type", 0);
        }
        
        $DB = M("vote_options");
        
        //获取投票项目的详情
        $res = $DB->find($vid);
        
        //获取发起人的信息
        $member = M("members")->find($res['mid']);
        
        $res['avatar'] = $member['avatar'];
        $res['username'] = $member['username'];
        
        $res['thumb_list']=  $this->get_one_thumb_list($res['img_ids']);
        
        $this->assign('result', $res);
        $this->assign("ip", get_client_ip());
        $this->display();
    }
    
    /*
     * 年货投票详情
     * 公众号进入的统计链接
     */
    public function detail_for_share() {
        
        /*
         * 增加页面访问量
         */
        $this->add_pv();
        
        $vid = I("get.vid");
        
        $promotion = I("get.promotion");
        if(empty($promotion))
        {
            $promotion=0;
        }
        
        $DB = M("vote_options");
        
        //获取投票项目的详情
        $res = $DB->find($vid);
        
        //获取发起人的信息
        $member = M("members")->find($res['mid']);
        
        $res['avatar'] = $member['avatar'];
        $res['username'] = $member['username'];
        
        $res['thumb_list']=  $this->get_one_thumb_list($res['img_ids']);
        
        $this->assign('result', $res);
        
//        print_r($res);
        $this->assign('promotion', $promotion);
        
        $this->assign("ip", get_client_ip());
        
        $this->display();
        
        
    }
    
    /*
     * 
     * 投票
     * 1. 判断是否关注
     * 
     * 2. 判断是否已经投票
     * 
     * 
     */
    public function vote_it() {
        
        /*
         * 增加页面访问量
         */
        $this->add_pv();
        $vsid = I("get.vsid");
        
        /*
         * 判断投票时间是否结束
         */
        $DB_vote_specials = M("vote_specials");
        $vs_res = $DB_vote_specials->find($vsid);
        if($vs_res['etime']<I("server.REQUEST_TIME"))
        {
            $result['err']=10;
            $result['content']="亲，本期投票活动完满结束，谢谢亲的积极参与，更多详情，请留意官方公众号！";

            echo json_encode($result);
            exit();
        }
        
//        判断当前时间是否是0：00 到 5：00，如果是，则不能投票
        $hh = date("H",I('server.REQUEST_TIME'));
        $hh_arr = array("00","01","02","03","04","05");
        if(in_array($hh, $hh_arr))
        {
            $result['err']=10;
            $result['content']="亲，早点休息啦，睡个美觉起来后再投票咯！";

            echo json_encode($result);
            exit();
        }
        
        $vid = I("get.vid");
        $openid = $this->memberinfo['wxopenid'];
        $mid = $this->memberinfo['id'];
        $cdate = date("Ymd",I('server.REQUEST_TIME'));
        $ip = I("get.ip");
        
        if($this->chk_member_is_fan($openid))
        {
            /*
             * 判断是否是自己给自己投票
             */
            $res_v_option = M("vote_options")->find($vid);
            
            if(!empty($res_v_option))
            {
                if($mid===$res_v_option['mid'])
                {
                    //不可以自己给自己投票
                    $result['err']=9;
                    $result['content']="亲，自己不可以给自己投票啦！";
                    
                    echo json_encode($result);
                    exit();
                    
                }
            }
            
            if(!$this->chk_if_vote_repeat($openid, $cdate))
            {
                $DB = M("vote_records");

                $map['vid']=$vid;
                $map['mid']=$mid;
                $map['cdate']=date("Ymd",I('server.REQUEST_TIME'));
                $map['ctime']=I('server.REQUEST_TIME');
                $map['openid']=$openid;
                
                $map['ipaddress']=$ip;

                $id = $DB->add($map);
                
                /*
                 * 投票加1
                 * 
                 */
                $DB_options = M("vote_options");
                $DB_options->where("id=".$vid)->setInc("vote_count");
                
                
                $result['err']=0;
                $result['content']="http://".I('server.HTTP_HOST')."/Public/template/default//img/vote/share_bg_01.png";

                
                
            }
            else 
            {
                //投票失败，不能重复投票
                
                $result['err']=1;
                $result['content']="http://".I('server.HTTP_HOST')."/Public/template/default//img/vote/share_bg_02.png";
            }

        }
        else
        {
//            还不是关注用户，不能参与投票，返回关注的二维码链接
            $res = M("vote_options")->find($vid);
            
            $result['err']=2;
            $result['content']=$res['qrcode_url'];
        }
        
        echo json_encode($result);
        
        
        
        
    }
    
    
    /*
     * 年货排行榜
     */
    public function ranks() {
        /*
         * 增加页面访问量
         */
        $this->add_pv();
        
        //按照人气排行
            $vsid = I("get.vsid");
            
            $DB = M("vote_options");
            if(empty($vsid))
            {
                $vsid=1;
            }
            
            $map['vsid']=$vsid;
            $map['ishidden']=0;
            
//            $res = $DB->where($map)->select();
            
            $count      = $DB->where($map)->count();// 查询满足要求的总记录数
            $Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
            $show       = $Page->show();// 分页显示输出
            //
            $res = $DB->where($map)->order('rank,vote_count DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
                    //
            //找出封面图片
            foreach ($res as $key => $value) {
                $res[$key]['thumb_list']=  $this->get_one_thumb_list($value['img_ids']);
            }
            
            $this->assign('page',$show);// 赋值分页输出
            $this->assign("result", $res);
            
            $initial_info = $this->_initial_info();
            $this->assign("initial_info", $initial_info);

            $this->display();
    }
    
    /*
     * 中奖结果公布
     */
    public function prizes() {
        /*
         * 增加页面访问量
         */
        $this->add_pv();
        
    }
    
    
    /*
     * 得奖攻略
     */
    public function steps() {
        /*
         * 增加页面访问量
         */
        $this->add_pv();
        
        header('Location:http://w.url.cn/s/AX4XOna');
//        $this->display();
    }
    
    /*
     * 返回请求，得到用户是否是粉丝
     */
    
    public function get_member_status() {
        $openid = $this->memberinfo['wxopenid'];
        $res = $this->chk_member_is_fan($openid);
        if($res)
        {
            echo 1;
        }
        else
        {
            echo 0;
        }
    }






    /*
     * 判断用户是否是关注用户
     * 返回 True OR False
     * 
     */
    private function chk_member_is_fan($openid) {
        $DB = M("members_subscribe_records");
        
        $map['openid']=$openid;
        $map['issubscribe']=1;
        
        $res = $DB->where($map)->find();
        if(!empty($res))
        {
            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }
    
    
    /*
     * 判断用户是否重复投票
     * 已投票 true
     * 未投票 false
     */
    private function chk_if_vote_repeat($openid,$cdate) {
        $DB = M("vote_records");
        $map['openid']=$openid;
        $map['cdate']=$cdate;
        
        $res = $DB->where($map)->find();
        
        if(!empty($res))
        {
            return TRUE;
        }
        else
        {
            return FALSE;
        }
        
        
    }
    
//    public function test() {
//        $res = $this->create_qrcode(1);
//        print_r($res);
//    }
    
    
    /*
     * 生成关注的临时二维码
     * 通过 vid（发起投票的选项的id 来生成临时二维码参数，因为临时二维码只支持 数字 ）
     */
    private function create_qrcode($vid) {
        $accessToken = $this->getAccessToken();
        $wxsdk = new \Com\WechatAuth(C('appid'), C('appsecret'),$accessToken);
        
        $qrcode_res = $wxsdk->qrcodeCreate($vid,"",2592000);
        // print_r($qrcode_res); die;
        if(!isset($qrcode_res['errcode'])){

            //不存在 errcode 则说明得到正常返回数据
            $qrcode_img = $this->get_qrcode_by_ticket($qrcode_res['ticket']);
            
            return $qrcode_img;
//            $res['qrcode_img'] = $qrcode_img;
//            $res['scene_str'] = $scene_str;
            
        }
        else
        {
            return FALSE;
        }
        
        
    }
    
    
    
    /*
     * 保存access_token 的最新状态
     * 
     */
    private function getAccessToken() {

        $jssdk = new \Com\JSSDK(C('appid'), C('appsecret'));
        $access_token = $jssdk->returnAccessToken();
        return $access_token;
    }
    
    /**
     * 通过ticket获取二维码图片
     * 
     */
    private function get_qrcode_by_ticket($ticket){


        $ticket = urlencode($ticket);

        $url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$ticket;

        return $url;
    }
    
    /*
     * 插入图片到fd_fundings_image表
     */
    private function insert_image($img_url)
    {
        $DB = M("fundings_image");
        $data['img_url']=$img_url;
        
        $id = $DB->add($data);
        
        return $id;
        
    }
    
    /*
     * 获取多张图片数组
     */
    
    private function get_one_thumb_list($detail_thumb_ids) {
//        $DB = M("fundings");
//        
//        $res = $DB->find($fdid);
//        
//        $thumb[]=$res['thumb'];
//        
//        
        
        $coverid = explode(",", $detail_thumb_ids);
        
        foreach($coverid as $key=>$value)
        {
            $thumb[] = M("fundings_image")->where('id='.$value)->getField('img_url');
        }
//        print_r($detail_thumb_ids);
        
        return $thumb;
        
        
    }
    
    
    /*
     * 获取初始化信息
     * 1. 已报名
     * 2. 获奖人数
     * 3. 访问量
     * 
     */
    private function _initial_info() {
        $map['ishidden']=0;
        $data['vote_option_count'] = M("vote_options")->where($map)->count();
        
        $data['got_prize_count']=M("vote_records")->count();
        
        $data['pv']=M("vote_setting")->where("id=1")->getField("keyvalue");
        
        return $data;
        
        
    }
    
        private function add_pv() {
//        增加访问量
        M("vote_setting")->where("id=1")->setInc("keyvalue");
        
    }
    
    
    /*
     * 刷新用户的作品排名
     */
    public function refresh_rank2() {
        $sql = "select vid,count(id) as number_count from `fd_vote_records`  group by vid order by number_count DESC";
        
        $DB = M("vote_options");
        
        $res = $DB->query($sql);
        
        /*
         * 更新一下排名
         */
        foreach ($res as $key => $value) {
            $DB->id = $value['vid'];
            $DB->rank = $key+1;
            $DB->save();
        }
        
        
//        print_r($res);
    }
    
    public function refresh_rank() {
        $sql = "select id,vote_count from `fd_vote_options` where ishidden=0 order by vote_count DESC,ctime";
        
        $DB = M("vote_options");
        
        $res = $DB->query($sql);
        
        foreach ($res as $key=>$value)
        {
            $DB->id = $value['id'];
            $DB->rank = $key+1;
            $DB->save();
        }
        
    }
    
     public function refresh_rank3() {
        $sql = "select id,vote_count from `fd_vote_options` order by vote_count DESC,ctime";
        
        $DB = M("vote_options");
        
        $res = $DB->query($sql);
        print_r(json_encode($res));
        exit();
        foreach ($res as $key=>$value)
        {
            $DB->id = $value['id'];
            $DB->rank = $key+1;
            $DB->save();
        }
        
    }
    
    
    /*
     * 生成随机验cash_code
     */
    private function create_ramdon_code(){
        mt_srand((double) microtime() * 1000000);
        return  str_pad(mt_rand(1, 99999999), 8, '0', STR_PAD_LEFT);
        
        /*
         * 检查code是否存在
         */
//        $DB = M("vote_options");
//        $map['cash_code']=$random_code;
//        
//        $res = $DB->where($map)->find();
//        
//        if(empty($res))
//        {
//            return $random_code;
//        }
//        else
//        {
//            
//        }
    }
    
    public function memberinfo() {
        print_r(session());
    }
    
    public function ip() {
        $ip = get_client_ip();
        echo $ip;
    }
    
    

   
}